package com.zixuan.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zixuan.common.Result;
import com.zixuan.common.dto.DeviceMangerRequestDTO;
import com.zixuan.dao.DeviceDao;
import com.zixuan.entity.DeviceMannerEntity;
import com.zixuan.service.DeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class DeviceServiceImpl implements DeviceService {

    @Autowired
    private DeviceDao deviceDao;
    @Override
    public Result addDevice(DeviceMannerEntity deviceMannerEntity) {

        return deviceDao.insert(deviceMannerEntity)>0? Result.ok() : Result.err();
    }

    @Override
    public Result findDeviceById(String deviceId) {
        DeviceMannerEntity mannerEntity = deviceDao.selectById(deviceId);
        if(mannerEntity==null){
            throw new RuntimeException("当前设备不存在");
        }
        return new Result(200,true,"SUCCESS",mannerEntity);
    }

    @Override
    public Result findAllDevice(String start, String end) {
        IPage<DeviceMannerEntity> page=new Page<DeviceMannerEntity>(Integer.parseInt(start),Integer.parseInt(end));
        IPage<DeviceMannerEntity> result = deviceDao.selectPage(page, null);
        if(result==null){
            throw new RuntimeException("当前没有数据");
        }
        return new Result(200,true,"SUCCESS",result);
    }

    @Override
    public Result delDeviceBydIds(String id) {
        return deviceDao.deleteById(id)>0 ? Result.ok() : Result.err();
    }

    @Override
    public Result updateDevice(DeviceMannerEntity deviceMannerEntity) {
        return deviceDao.updateById(deviceMannerEntity)>0 ? Result.ok(): Result.err();
    }

    @Override
    public Result findDeviceByCondition(DeviceMangerRequestDTO dto) {
        Page<DeviceMannerEntity> page=new Page<>();
        QueryWrapper<DeviceMannerEntity> wrapper = new QueryWrapper<>();
        if(!StringUtils.isEmpty(dto.getDeviceName())){
            wrapper.like("device_name",dto.getDeviceName());
        }
        if(!StringUtils.isEmpty(dto.getDeviceStatus())){
            wrapper.eq("device_status",dto.getDeviceStatus());
        }
        if(!StringUtils.isEmpty(dto.getDeviceType())){
            wrapper.eq("device_type",dto.getDeviceType());
        }
        Page<DeviceMannerEntity> pageList = deviceDao.selectPage(page, wrapper);

        return new Result(200,true,"SUCCESS",pageList);
    }


}
